package com.hzx.zhihu.utils;

import com.alibaba.fastjson.JSON;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;


public class WeChatUtil {

    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/CBC/PKCS5Padding";

    public static Object decryptData(String sessionKey, String encryptedData, String iv) throws Exception {
        // 解码
        byte[] sessionKeyBytes = Base64.decodeBase64(sessionKey);
        byte[] encryptedDataBytes = Base64.decodeBase64(encryptedData);
        byte[] ivBytes = Base64.decodeBase64(iv);

        // 创建密码器
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        SecretKeySpec keySpec = new SecretKeySpec(sessionKeyBytes, ALGORITHM);
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

        // 解密
        byte[] result = cipher.doFinal(encryptedDataBytes);
        String resultString = new String(result, StandardCharsets.UTF_8);

        // 反序列化为JSON对象
        return JSON.parse(resultString);
    }
}
